﻿using System;
using System.IO;
using System.Reflection;

namespace ICommonLibrary.Resource {

    public class AssemblyUtil {

        public static Stream LoadResource(string assemblyString, string resourcePath) {
            return LoadResource(Assembly.Load(assemblyString), resourcePath);
        }

        public static Stream LoadResource(Type type, string resourcePath) {
            return LoadResource(type.Assembly, resourcePath);
        }

        public static Stream LoadResource(Assembly assembly, string resourcePath) {
            Stream resource = assembly.GetManifestResourceStream(assembly.GetName().Name + '.' + resourcePath);
            return resource;
        }

        public static string LoadTextResource(string assemblyString, string resourcePath) {
            return IOUtil.ReadStringAndClose(LoadResource(assemblyString, resourcePath));
        }

        public static string LoadTextResource(Type type, string resourcePath) {
            return IOUtil.ReadStringAndClose(LoadResource(type, resourcePath));
        }

        public static string LoadTextResource(Assembly assembly, string resourcePath) {
            return IOUtil.ReadStringAndClose(LoadResource(assembly, resourcePath));
        }

        /// <summary>
        /// An example of resource string is
        /// 
        ///   Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
        /// 
        /// </summary>
        /// <param name="resourceString"></param>
        /// <returns></returns>
        public static AssemblyResource ReadResouceString(string resourceString) {
            int comma = resourceString.IndexOf(',');
            if (comma == -1) {
                throw new ArgumentException("Couldn't find assembly string");
            }
            string resourcePath = resourceString.Substring(0, comma);
            string assemblyString = Util.Substring(resourceString, comma + 1, resourceString.Length);
            return new AssemblyResource(assemblyString, resourcePath);
        }

    }
}
